package fun.huixi.weiju.security;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import fun.huixi.weiju.pojo.entity.WjUser;
import fun.huixi.weiju.service.WjUserService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;

/**
 * 自定义登录验证
 *
 * @Author Sans
 * @CreateTime 2019/10/1 19:11
 */
@Component
public class UserAuthenticationProvider implements AuthenticationProvider {

    @Resource
    private WjUserService wjUserService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        // 获取表单输入中返回的手机号码
        String nickName = (String) authentication.getPrincipal();
        // 获取表单中输入的密码
        String password = (String) authentication.getCredentials();

        if (StrUtil.isBlank(nickName)) {
            throw new UsernameNotFoundException("用户名不存在");
        }

        // 查询用户是否存在
        WjUser userInfo = wjUserService.loadUserByNickName(nickName);
        if (userInfo == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }

        // 我们还要判断密码是否正确，密码使用 hutool的md5
        String md5Password = SecureUtil.md5(password);
        String userPassword = userInfo.getPassword();
        boolean equals = md5Password.equals(userPassword);
        if (!equals) {
            throw new BadCredentialsException("密码不正确");
        }
        // 还可以加一些其他信息的判断，比如用户账号已停用等判断
//        if (userInfo.getStatus().equals("PROHIBIT")) {
//            throw new LockedException("该用户已被冻结");
//        }

        // 角色集合
        Set<GrantedAuthority> authorities = new HashSet<>();
        // 查询用户角色
//        List<SysRoleEntity> sysRoleEntityList = sysUserService.selectSysRoleByUserId(userInfo.getUserId());
//        for (SysRoleEntity sysRoleEntity : sysRoleEntityList) {
//            authorities.add(new SimpleGrantedAuthority("ROLE_" + sysRoleEntity.getRoleName()));
//        }
        userInfo.setAuthorities(authorities);
        // 进行登录
        return new UsernamePasswordAuthenticationToken(userInfo, authorities);
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return true;
    }


}